package com.meixiang.activity.account.myfund;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.WebviewActivity;
import com.meixiang.adapter.myFundAdapter.DealRecordAdapter;
import com.meixiang.adapter.myFundAdapter.EarningsRecordAdapter;
import com.meixiang.dialog.ProfitDialogFragment;
import com.meixiang.entity.fund.FundHoldingDetial;
import com.meixiang.entity.fund.FundHoldingDetialBean;
import com.meixiang.entity.fund.FundProfitRecord;
import com.meixiang.entity.fund.FundTradeRecodeBean;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbStrUtil;
import com.meixiang.view.TitleView;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Response;

/**
 * 基金详情页
 * Created by xyj on 2016/5/31.
 */
public class FundDetialActivity extends BaseActivity implements OnLoadMoreListener, OnRefreshListener {
    public static final String TAG = "FundDetialActivity";
    @Bind(R.id.title)
    TitleView titleView; //头部视图
    @Bind(R.id.refresh)
    SwipeToLoadLayout mLayout;
    @Bind(R.id.swipe_target)
    RecyclerView recyclerView;
    RelativeLayout rl_botton_layout; //分红方式
    @Bind(R.id.ll_bottom_layout)
    LinearLayout ll_bottom_layout;
    @Bind(R.id.tv_fund_detail_buy)
    TextView tv_fund_detail_buy; // 买入
    @Bind(R.id.tv_fund_detail_redeem)
    TextView tv_fund_detail_redeem; // 卖出
    private String titleName;
    private View headerView;
    private DealRecordAdapter dealRecordAdapter; //交易记录
    private EarningsRecordAdapter earningsRecordAdapter; //收益记录
    private TextView tv_earnings_record, tv_deal_record, tv_melon_method_type; //
    private TextView trade_total_money, flow_profit_yesterday, market_value, underway_amount_all, holding_balance, flow_profit_all, nav, nav_date;
    private TextView trade_total_money_name, flow_profit_yesterday_name, market_value_name, underway_amount_all_name, holding_balance_name, flow_profit_all_name, nav_name, nav_date_name;
    private String id;
    private String fund_id;
    private String type = "0"; //0持有详情，1交易记录，2收益记录
    private int page = 1;
    private int pageSize = 10;
    private FundHoldingDetial mFundDetial;
    private List<FundProfitRecord> fund_profit_recordList; //收益记录
    private List<FundTradeRecodeBean> fund_trade_recode; //交易记录
    private boolean isLoadMore = false;
    private ProfitDialogFragment profitDialogFragment;
    private FundHoldingDetialBean fund_holding_detail;
    private String melon_method = null;
    private String show_title = null ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_fund_detail);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {
        titleName = getIntent().getStringExtra("titleName");
        id = getIntent().getStringExtra("id");
        fund_id = getIntent().getStringExtra("fund_id");

        
    }

    @Override
    protected void initView() {
        initHeaderView();
        titleView.setBackgroundColor(ContextCompat.getColor(context, R.color.fund_money_color));
        titleView.setTitle(titleName);
        titleView.setLeftImageButton(R.mipmap.month_3);
        titleView.setRightTextButton("详情");
        titleView.setRightTextCorlr(ContextCompat.getColor(context, R.color.white));
        titleView.showLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleView.showRightButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, WebviewActivity.class);
                intent.putExtra("title", titleName);
                intent.putExtra("url", Config.FUND_INFO_NEW + "?fund_id=" + fund_id);
                startActivity(intent);
            }
        });

        titleView.setTColor(ContextCompat.getColor(context, R.color.white));
        tv_earnings_record.setOnClickListener(this);
        tv_deal_record.setOnClickListener(this);
        tv_fund_detail_buy.setOnClickListener(this);
        tv_fund_detail_redeem.setOnClickListener(this);
        mLayout.setOnLoadMoreListener(this);
        mLayout.setOnRefreshListener(this);
    }

    /**
     * 初始化头部视图
     */
    private void initHeaderView() {
        headerView = LayoutInflater.from(context).inflate(R.layout.fund_detail_header_view, null);
        tv_earnings_record = (TextView) headerView.findViewById(R.id.tv_earnings_record);
        tv_deal_record = (TextView) headerView.findViewById(R.id.tv_deal_record);
        rl_botton_layout = (RelativeLayout) headerView.findViewById(R.id.rl_botton_layout);
        trade_total_money = (TextView) headerView.findViewById(R.id.trade_total_money);
        flow_profit_yesterday = (TextView) headerView.findViewById(R.id.flow_profit_yesterday);
        market_value = (TextView) headerView.findViewById(R.id.market_value);
        underway_amount_all = (TextView) headerView.findViewById(R.id.underway_amount_all);
        holding_balance = (TextView) headerView.findViewById(R.id.holding_balance);
        flow_profit_all = (TextView) headerView.findViewById(R.id.flow_profit_all);
        tv_melon_method_type = (TextView) headerView.findViewById(R.id.tv_melon_method_type);
        nav = (TextView) headerView.findViewById(R.id.nav);
        nav_date = (TextView) headerView.findViewById(R.id.nav_date);
        trade_total_money_name = (TextView) headerView.findViewById(R.id.trade_total_money_name);
        flow_profit_yesterday_name = (TextView) headerView.findViewById(R.id.flow_profit_yesterday_name);
        market_value_name = (TextView) headerView.findViewById(R.id.market_value_name);
        underway_amount_all_name = (TextView) headerView.findViewById(R.id.underway_amount_all_name);
        holding_balance_name = (TextView) headerView.findViewById(R.id.holding_balance_name);
        flow_profit_all_name = (TextView) headerView.findViewById(R.id.flow_profit_all_name);
        nav_name = (TextView) headerView.findViewById(R.id.nav_name);
        nav_date_name = (TextView) headerView.findViewById(R.id.nav_date_name);
    }

    /**
     * setHeaderViewData
     * 填充头部视图数据
     */
    private void setHeaderViewData() {
        ll_bottom_layout.setVisibility(View.VISIBLE);
        melon_method = fund_holding_detail.getMelon_method(); //展示的分红方式
        show_title = fund_holding_detail.getShow_title() ;
        if ("0".equals(fund_holding_detail.getIs_buy())) { // 表示买入按钮可用
            tv_fund_detail_buy.setBackgroundColor(ContextCompat.getColor(context, R.color.fund_money_color));
            tv_fund_detail_buy.setEnabled(true);
        } else { // 表示买入按钮不可用
            tv_fund_detail_buy.setBackgroundColor(ContextCompat.getColor(context, R.color.fund_is_buy_redeem_used_color));
            tv_fund_detail_buy.setEnabled(false);
        }
        if ("0".equals(fund_holding_detail.getIs_redeem())) { // 表示卖出按钮可用
            tv_fund_detail_redeem.setEnabled(true);
            tv_fund_detail_redeem.setBackgroundColor(ContextCompat.getColor(context, R.color.fund_money_color));
        } else {// 表示卖出按钮不可用
            tv_fund_detail_redeem.setEnabled(false);
            tv_fund_detail_redeem.setBackgroundColor(ContextCompat.getColor(context, R.color.fund_is_buy_redeem_used_color));
        }
        if ("0".equals(fund_holding_detail.getMelon_method())) { //分红方式0红利再投1现金分红
            if ("0".equals(fund_holding_detail.getMelon_method_type())) {
                tv_melon_method_type.setText("红利再投");
                rl_botton_layout.setOnClickListener(this);
            } else {
                tv_melon_method_type.setText("红利再投(更改中)");
            }
        } else {
            if ("0".equals(fund_holding_detail.getMelon_method_type())) {
                tv_melon_method_type.setText("现金分红");
                rl_botton_layout.setOnClickListener(this);
            } else {
                tv_melon_method_type.setText("现金分红(更改中)");
            }
        }
        trade_total_money.setText(AbStrUtil.ChangeF3D(fund_holding_detail.getTrade_total_money()));
        if(fund_holding_detail.getFlow_profit_yesterday().contains("-")){
            flow_profit_yesterday.setText(AbStrUtil.ChangeF3D(fund_holding_detail.getFlow_profit_yesterday()));
        }else{
            flow_profit_yesterday.setText("+"+AbStrUtil.ChangeF3D(fund_holding_detail.getFlow_profit_yesterday()));
        }
        market_value.setText(AbStrUtil.ChangeF3D(fund_holding_detail.getMarket_value()));
        underway_amount_all.setText(AbStrUtil.ChangeF3D(fund_holding_detail.getUnderway_amount_all()));
        holding_balance.setText(fund_holding_detail.getHolding_balance());
        if(fund_holding_detail.getFlow_profit_all().contains("-")){
            flow_profit_all.setText(AbStrUtil.ChangeF3D(fund_holding_detail.getFlow_profit_all()));
        }else{
            flow_profit_all.setText("+"+AbStrUtil.ChangeF3D(fund_holding_detail.getFlow_profit_all()));
        }
        nav.setText(fund_holding_detail.getNav());
        nav_date.setText(fund_holding_detail.getNav_date());
        trade_total_money_name.setText(fund_holding_detail.getTrade_total_money_name());
        flow_profit_yesterday_name.setText(fund_holding_detail.getFlow_profit_yesterday_name());
        market_value_name.setText(fund_holding_detail.getMarket_value_name() + ":");
        underway_amount_all_name.setText(fund_holding_detail.getUnderway_amount_all_name() + ":");
        flow_profit_all_name.setText(fund_holding_detail.getFlow_profit_all_name() + ":");
        nav_name.setText(fund_holding_detail.getNav_name() + ":");
        holding_balance_name.setText(fund_holding_detail.getHolding_balance_name() + ":");
        nav_date_name.setText(fund_holding_detail.getNav_date_name() + ":");
    }

    @Override
    protected void setData() {
        getHttpHoldingNew();
        setEarningsRecordData();
        setDealRecordData();
    }

    /**
     * 获取基金详情数据
     */
    private void getHttpHoldingNew() {
        HttpParams params = new HttpParams();
        params.put("id", id);
        params.put("type", type);
        params.put("page", String.valueOf(page));
        params.put("pageSize", String.valueOf(pageSize));
        HttpUtils.post(Config.FUND_HOLDING_NEW, TAG, params, new HttpCallBack(this) {
            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                mLayout.setLoadingMore(false);
            }

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if (!"".equals(result.optJSONObject("data").optString("fund_trade_recode"))) {
                    mFundDetial = AbJsonUtil.fromJson(result.optString("data").toString(), new TypeToken<FundHoldingDetial>() {
                    });
                    if (mFundDetial != null && mFundDetial.getFund_trade_recode().size() != 0) {
                        if (isLoadMore) {
                            fund_trade_recode.addAll(mFundDetial.getFund_trade_recode());
                            dealRecordAdapter.refreshData(fund_trade_recode);
                            mLayout.setLoadingMore(false);
                        } else {
                            fund_trade_recode = mFundDetial.getFund_trade_recode();
                            dealRecordAdapter.refreshData(fund_trade_recode);
                            mLayout.setRefreshing(false);
                        }
                    }
                }
                if (!"".equals(result.optJSONObject("data").optString("fund_holding_detail"))) {
                    fund_holding_detail = AbJsonUtil.fromJson(result.optJSONObject("data").optString("fund_holding_detail").toString(), new TypeToken<FundHoldingDetialBean>() {
                    });
                    if (fund_holding_detail != null) {
                        setHeaderViewData();
                    }
                }
                if (result.optJSONObject("data").optString("fund_profit_record").contains("[")) {
                    JSONArray jsonArray = result.optJSONObject("data").optJSONArray("fund_profit_record");
                    fund_profit_recordList = new ArrayList<FundProfitRecord>();
                    if (jsonArray != null && jsonArray.length() != 0) {
                        for(int i=0;i<jsonArray.length();i++){
                            FundProfitRecord fundProfitRecord = new FundProfitRecord() ;
                            JSONObject jsonObject = jsonArray.optJSONObject(i);
                            fundProfitRecord.setNav_date(jsonObject.optString("nav_date"));
                            fundProfitRecord.setDay_rate(jsonObject.optString("day_rate"));
                            fundProfitRecord.setDay_profit(jsonObject.optString("day_profit"));
                            fundProfitRecord.setType(jsonObject.optString("type"));
                            fund_profit_recordList.add(fundProfitRecord);
                        }
                        if (isLoadMore) {
                            fund_profit_recordList.addAll(fund_profit_recordList);
                            earningsRecordAdapter.refreshData(fund_profit_recordList);
                            mLayout.setLoadingMore(false);
                        } else {
                            earningsRecordAdapter.refreshData(fund_profit_recordList);
                            mLayout.setRefreshing(false);
                        }
                    }
                }

            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context, message);
            }
        });

    }

    /**
     * 初始化收益记录
     */
    private void setEarningsRecordData() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        earningsRecordAdapter = new EarningsRecordAdapter(context);
        recyclerView.setAdapter(earningsRecordAdapter);
        earningsRecordAdapter.setHeaderView(headerView);
    }

    /**
     * 初始化交易记录
     */
    private void setDealRecordData() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        dealRecordAdapter = new DealRecordAdapter(context, FundDetialActivity.this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.rl_botton_layout:
                Bundle bundle = new Bundle();
                bundle.putString("fund_id", fund_id);
                if(melon_method!=null&&show_title!=null){
                    bundle.putString("melon_method",melon_method);
                    bundle.putString("show_title",show_title);
                }
                profitDialogFragment = new ProfitDialogFragment();
                profitDialogFragment.newInstance(bundle).show(getSupportFragmentManager(), ProfitDialogFragment.TAG);
                break;
            case R.id.tv_earnings_record: //收益
                type = "2";
                tv_earnings_record.setTextColor(ContextCompat.getColor(context, R.color.fund_money_color));
                tv_deal_record.setTextColor(ContextCompat.getColor(context, R.color.black_3));
                recyclerView.setAdapter(earningsRecordAdapter);
                break;

            case R.id.tv_deal_record: //交易
                type = "1";
                tv_earnings_record.setTextColor(ContextCompat.getColor(context, R.color.black_3));
                tv_deal_record.setTextColor(ContextCompat.getColor(context, R.color.fund_money_color));
                if (mFundDetial != null && mFundDetial.getFund_trade_recode() != null) {
                    dealRecordAdapter.refreshData(mFundDetial.getFund_trade_recode());
                    dealRecordAdapter.setHeaderView(headerView);
                    recyclerView.setAdapter(dealRecordAdapter);
                }
                break;

            case R.id.tv_fund_detail_buy:
                intent = new Intent(context, WebviewActivity.class);
                intent.putExtra("url", Config.FUND_BUY + "?fund_id=" + fund_id);
                intent.putExtra("title", "买入");
                startActivity(intent);
                break;

            case R.id.tv_fund_detail_redeem:
                intent = new Intent(context, WebviewActivity.class);
                intent.putExtra("url", Config.FUND_REDEEM_NEW + "?id=" + id);
                intent.putExtra("title", "卖出");
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onLoadMore() {
        page++;
        isLoadMore = true;
        getHttpHoldingNew();
    }

    @Override
    public void onRefresh() {
        isLoadMore = false;
        page = 1;
        getHttpHoldingNew();
    }
}
